﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace exMath.Common
{
    public class FunctionCache : Hashtable 
    {
        public FunctionCache()
            : base()
        {
            TimeStamp = DateTime.Now;
        }

        public DateTime TimeStamp { get; set; }

        public double this[double variable]
        {
            get 
            {
                if (base[variable] != null)
                    return (double)base[variable];
                else
                    return double.NaN;
            }

            set
            {
                base[variable] = value;
            }
        }

        public bool ResultExists(double Variable)
        {
            return double.IsNaN(this[Variable]);
        }
    }

    /// <summary>
    /// The global function cache.
    /// </summary>
    public class GFC
    {
        private static Hashtable _cache = new Hashtable();
        private static bool _performCaching = true;
        
        /// <summary>
        /// Turns the global function cache on- or off. This might be helpfull if memory fills up fast or when the GC slows down the execution speed of your functions.
        /// </summary>
        public static bool PerformCaching
        {
            get
            {
                return _performCaching;
            }

            set
            {
                _performCaching = value;
            }
        }

        public static void SetCacheItem(string FunctionID, FunctionCache Cache)
        {
            if (PerformCaching)
            {
                //for now add a timestamp for possible future auto-cleanup feature.
                Cache.TimeStamp = DateTime.Now;
                _cache[FunctionID] = Cache;
            }
        }

        public static FunctionCache GetCacheItem(string FunctionID)
        {
            if (_cache[FunctionID] == null)
                return new FunctionCache();
            else
                return (FunctionCache)_cache[FunctionID];
        }

        public static void Clear()
        {
            _cache.Clear();
        }
    }
}
